package com.yanqu.road.server.manager.activity.commonsupport;

import com.yanqu.road.dao.impl.activity.commonsupport.CommonUnionSupportDataDaoImpl;
import com.yanqu.road.dao.impl.activity.commonsupport.CommonUnionSupportUserDataDaoImpl;
import com.yanqu.road.entity.activity.commonsupport.CommonUnionSupportData;
import com.yanqu.road.entity.activity.commonsupport.CommonUnionSupportUserData;
import com.yanqu.road.entity.activity.commonsupport.config.CommonUnionSupportConfig;
import com.yanqu.road.pb.activity.CommonUnionSupportProto;
import com.yanqu.road.server.manager.activity.commonsupport.handler.SupportActivityHandler;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.List;
import java.util.Map;

public class CommonSupportActivity {

    CommonUnionSupportConfig config;

    int groupId;

    Map<String, CommonUnionSupportData> unionMap;

    Map<Long, CommonUnionSupportUserData> userMap;


    public CommonSupportActivity(CommonUnionSupportConfig config, int groupId) {
        this.config = config;
        this.groupId = groupId;
        this.reloadData();
    }

    private void reloadData() {
        unionMap = new CommonUnionSupportDataDaoImpl().getCommonUnionSupportData(config.getActivityInfo().getActivityId(), groupId);
        userMap = new CommonUnionSupportUserDataDaoImpl().getCommonUnionSupportUserData(config.getActivityInfo().getActivityId(), groupId);
    }

    public CommonUnionSupportProto.GetUnionSupportListResp.Builder getSupportList(long userId){

        CommonUnionSupportProto.GetUnionSupportListResp.Builder clientMsg = CommonUnionSupportProto.GetUnionSupportListResp.newBuilder();
        clientMsg.setRet(0);
        clientMsg.setMySupport("");
        CommonUnionSupportUserData userData = getUserData(userId);
        if(userData != null && !StringUtils.isNullOrEmpty(userData.getUnionUid())){
            clientMsg.setMySupport(userData.getUnionUid());
        }
        for (Map.Entry<String, CommonUnionSupportData> entry : unionMap.entrySet()) {
            CommonUnionSupportData data = entry.getValue();
            CommonUnionSupportProto.UnionSupportListTemp.Builder builder = CommonUnionSupportProto.UnionSupportListTemp.newBuilder();
            builder.setUnionUid(data.getUnionUid());
            builder.setHotCount(data.getHotCount());
            clientMsg.addSupport(builder);
        }

        return clientMsg;
    }

    /**
     * 支持
     * @param targetUnionOrUser 多个商会、多个玩家；逗号隔开
     */
    public CommonUnionSupportProto.DoUnionSupportResp.Builder support(long serverId, long playerId, String targetUnionOrUser) {
        CommonUnionSupportProto.DoUnionSupportResp.Builder respMsg = CommonUnionSupportProto.DoUnionSupportResp.newBuilder();
        respMsg.setRet(0);
        //资格处理
        SupportActivityHandler handler = SupportActivityHandler.get(config.getActivityInfo().getType());
        if(handler == null){
            respMsg.setRet(GameErrorCode.E_COMMON_SUPPORT_ACTIVITY_ABLE);
            return respMsg;
        }
        if(config.getSupportSwitch() == 0){
            respMsg.setRet(GameErrorCode.E_COMMON_SUPPORT_ACTIVITY_ABLE);
            return respMsg;
        }
        //判断时间
        long startTime = config.getActivityInfo().getBeginTime() * DateHelper.SECOND_MILLIONS + config.getSupportTimeList().get(0) * DateHelper.HOUR_MILLIONS;
        long endTime = config.getActivityInfo().getBeginTime() * DateHelper.SECOND_MILLIONS + config.getSupportTimeList().get(1) * DateHelper.HOUR_MILLIONS;
        long nowTime = System.currentTimeMillis();
        if(nowTime < startTime || nowTime > endTime){
            respMsg.setRet(GameErrorCode.E_COMMON_SUPPORT_NOT_IN_TIME);
            return respMsg;
        }

        //玩家资格
        boolean ableUser = handler.ableUser(config.getActivityInfo().getActivityId(), groupId, playerId);
        if(!ableUser){
            respMsg.setRet(GameErrorCode.E_COMMON_SUPPORT_USER_ABLE);
            return respMsg;
        }

        List<String> targetList = StringUtils.stringToStringList(targetUnionOrUser, ",");
        //支持名单资格
        for (String target : targetList) {
            boolean ableUnion = handler.ableUnion(config.getActivityInfo().getActivityId(), groupId, target);
            if(!ableUnion){
                respMsg.setRet(GameErrorCode.E_COMMON_SUPPORT_UNION_ABLE);
                return respMsg;
            }
        }

        CommonUnionSupportUserData userData = getCommonUnionSupportUserData(playerId);
        //记录支持名单，设置奖励标识
        synchronized (userData) {
            if (!StringUtils.isNullOrEmpty(userData.getUnionUid()) || userData.getGetReward() == 1) {
                respMsg.setRet(GameErrorCode.E_COMMON_SUPPORT_REPEATED);
                return respMsg;
            }
            userData.setUnionUid(targetUnionOrUser);
            userData.setGetReward(1);
        }
        respMsg.setMySupport(targetUnionOrUser);
        respMsg.setReward(config.getReward());

        //支持热度+1
        for (String target : targetList) {
            CommonUnionSupportData supportData = getCommonUnionSupportData(target);
            synchronized (supportData){
                supportData.setHotCount(supportData.getHotCount() + 1);
            }
            CommonUnionSupportProto.UnionSupportListTemp.Builder builder = CommonUnionSupportProto.UnionSupportListTemp.newBuilder();
            builder.setUnionUid(target);
            builder.setHotCount(supportData.getHotCount());
            respMsg.addSupport(builder);
        }

        return respMsg;
    }


    public CommonUnionSupportUserData getCommonUnionSupportUserData(long userId){
        CommonUnionSupportUserData data = userMap.get(userId);
        if(data == null){
            synchronized (userMap){
                data = userMap.get(userId);
                if(data == null){
                    data = new CommonUnionSupportUserData();
                    data.setActivityId(config.getActivityInfo().getActivityId());
                    data.setGroupId(groupId);
                    data.setUserId(userId);
                    data.setUnionUid("");
                    data.setInsertOption();
                    userMap.put(data.getUserId(), data);
                }
            }
        }
        return data;
    }

    public CommonUnionSupportData getCommonUnionSupportData(String unionUid){
        CommonUnionSupportData data = unionMap.get(unionUid);
        if(data == null){
            synchronized (unionMap){
                data = unionMap.get(unionUid);
                if(data == null){
                    data = new CommonUnionSupportData();
                    data.setActivityId(config.getActivityInfo().getActivityId());
                    data.setGroupId(groupId);
                    data.setUnionUid(unionUid);
                    data.setInsertOption();
                    unionMap.put(data.getUnionUid(), data);
                }
            }
        }
        return data;
    }

    public void saveData(){

        for (Map.Entry<String, CommonUnionSupportData> entry : unionMap.entrySet()) {
            CommonUnionSupportData data = entry.getValue();
            if(data.isInsertOption()){
                new CommonUnionSupportDataDaoImpl().add(data);
            }else if(data.isUpdateOption()){
                new CommonUnionSupportDataDaoImpl().update(data);
            }
        }

        for (Map.Entry<Long, CommonUnionSupportUserData> entry : userMap.entrySet()) {
            CommonUnionSupportUserData data = entry.getValue();
            if(data.isInsertOption()){
                new CommonUnionSupportUserDataDaoImpl().add(data);
            }else if(data.isUpdateOption()){
                new CommonUnionSupportUserDataDaoImpl().update(data);
            }
        }
    }

    public CommonUnionSupportUserData getUserData(long userId){
        return userMap.get(userId);
    }



}
